const express = require('express');
const bp = require('body-parser');
const path = require('path')
const mount = require('mount-routes')
const setting = require('./setting.js')
const verify = require('./config/verify.js')
const expressJwt = require('express-jwt')

const app = express();

app.use(bp.urlencoded({extend: true}))
app.use(bp.json())

// 设置跨域和相应数据格式
app.all('/*', function(req, res, next) {
  res.header('Access-Control-Allow-Origin', '*')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, mytoken')
  res.header('Access-Control-Allow-Headers', 'X-Requested-With, Authorization')
  res.setHeader('Content-Type', 'application/json;charset=utf-8')
  res.header('Access-Control-Allow-Headers', 'Content-Type,Content-Length, Authorization, Accept,X-Requested-With')
  res.header('Access-Control-Allow-Methods', 'PUT,POST,GET,DELETE,OPTIONS')
  res.header('X-Powered-By', ' 3.2.1')
  if (req.method == 'OPTIONS') res.send(200)
  /*让options请求快速返回*/ else next()
})

//匹配所有请求，把请求中的token取出并解析
//
app.use((req, res, next) => {
	// 获取请求头中的参数
    let token = req.headers[setting.token.header]
    if(token === undefined){
        return next()
    }else{
    	// token校验并将校验结果保存至请求头中
        verify.getToken(token).then(data => {
            req.data = data
            return next()
        }).catch(_ =>{
            return next()
        })
    }
})
//验证token是否过期并规定哪些路由不用验证
app.use(expressJwt({
    secret: setting.token.signKey,
	algorithms: ['HS256']
}).unless({
    //除了这个地址，其他的URL都需要验证
    path: setting.token.unRoute 
}))

//当token失效返回提示信息
app.use((err, req, res, next) => {
    if (err.status === 401) {
        return res.status(err.status).json({
            status: err.status,
            msg: 'The token is invalid',
            error: err.name + ':' + err.message
        })
    }
})


//引入所有的路由  process.cwd()获得当前文件路径
mount(app,path.join(process.cwd(),'/router'),true)

//开启web服务器
app.listen(8890)

module.exports = app;